package jmine.tec.web.wicket.component.autocomplete;

import jmine.tec.persist.naturalkey.NaturalKeyHandler;
import jmine.tec.persist.naturalkey.NaturalKeyHandlerFactory;
import jmine.tec.utils.spring.SpringBeanReference;

import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AbstractAutoCompleteTextRenderer;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.IAutoCompleteRenderer;

import bancosys.tec.persist.Persistable;
import bancosys.tec.persist.exception.NaturalKeyNotDefinedException;

/**
 * @see org.apache.wicket.extensions.ajax.markup.html.autocomplete.StringAutoCompleteRenderer
 * @param <P> o tipo
 * @author seiti
 */
public final class NaturalKeyAutoCompleteTextRenderer<P> extends AbstractAutoCompleteTextRenderer<P> {

    /**
     * A singleton instance
     */
    public static final IAutoCompleteRenderer INSTANCE = new NaturalKeyAutoCompleteTextRenderer();

    /**
     * Ctor
     */
    private NaturalKeyAutoCompleteTextRenderer() {
        //
    }
    
    /**
     * @param <T> type
     * @return A static instance of the class
     */
    @SuppressWarnings("unchecked")
    public static <T> IAutoCompleteRenderer<T> instance() {
        return INSTANCE;
    }

    /**
     * @see AbstractAutoCompleteTextRenderer#getTextValue(Object)
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    @Override
    protected String getTextValue(Object object) {
        SpringBeanReference<NaturalKeyHandlerFactory> ref = SpringBeanReference.forType(NaturalKeyHandlerFactory.class);
        NaturalKeyHandler handler = ref.get().findNaturalKeyProperties((Class<? extends Persistable>) object.getClass());
        if (handler == null) {
            throw new NaturalKeyNotDefinedException(object.getClass());
        }
        return handler.getNaturalKey((Persistable) object).toString();
    }

}
